from datetime import datetime
import urwid.curses_display
import twitter
import urwid

class Conversation(object):
    def __init__(self):
        self.update_messages = urwid.SimpleListWalker(self.get_updates())
        self.debug_messages = urwid.SimpleListWalker([urwid.Text("Awesome!")])
        self.items = self.update_messages
        self.listbox = urwid.ListBox(self.items)
        header = urwid.AttrWrap(urwid.Text('Press F8 to exit'), 'header')
        footer = urwid.AttrWrap(urwid.Edit('>>> '), 'footer')
        self.frame = urwid.Frame(self.listbox, header = header, footer = footer)
        self.frame.set_focus('footer')

    def main(self):
        self.ui = urwid.curses_display.Screen()
        self.ui.register_palette([
            ('header', 'black', 'dark cyan', 'standout'),
            ('footer', 'black', 'dark cyan', 'standout'),
            ('I say', 'default', 'default', 'bold'),
            ])
        self.ui.run_wrapper(self.run)
     
    def run(self):
        """The main program loop"""

        size = self.ui.get_cols_rows()

        while True:
            self.draw_screen(size)
            keys = self.ui.get_input()

            if "f8" in keys:
                break
            for k in keys:
                if k == "window resize":
                    size = self.ui.get_cols_rows()
                    continue

                elif k == 'meta 1':
                    self.items = self.debug_messages
                elif k == 'meta 2':
                    self.items = self.update_messages
                elif k == 'f5':
                    pos = self.listbox.get_focus()[1]
                    self.items[:0] = (self.get_updates())
                    if self.get_updates():
                        self.listbox.set_focus(pos + 1, coming_from='above')
                else:
                    self.keypress(size, k)

    def keypress(self, size, k):
        """The keypress routine, processes pressed key"""

        if k == "enter":
            self.post_update()
        else:
            self.frame.keypress(size, k)

    def post_update(self):
        """Posts a new update"""

        api.PostUpdate(self.frame.footer.get_edit_text())
        self.frame.footer.set_edit_text('')
 
    def draw_screen(self, size):
        """Renders screen"""

        canvas = self.frame.render(size, focus=True)
        self.ui.draw_screen(size, canvas)

    def get_updates(self):
        """Passes a list of widgets created out of twitter updates"""

        update_list = []
        for update in api.GetFriendsTimeline():
            update_list.append(self.wrap_in_widget(update.text, update.relative_created_at, update.user.screen_name))
        return update_list

    def wrap_in_widget(self, text, timestamp, username):
        """Wraps given strings into a columnn widget ready to be thrown into listbox"""

        col1 = ('weight', 0.1, urwid.Text(username))
        col2 = ('weight', 0.65, urwid.Text(text))
        col3 = ('weight', 0.25, urwid.Text(timestamp))
        return urwid.Columns([col1, col2, col3], dividechars = 1)

if __name__ == "__main__":
    api = twitter.Api(username = 'artagnon', password = """sesame""")
    Conversation().main()
